
class RGB {
  constructor(r, g, b) {
    this.r = r;
    this.g = g;
    this.b = b;
  }
}

/**
 * 提供颜色值计算辅助函数
 */

  //RGB转十六进制
var rgb_to_hex = function (rgb) {
    var hex = ((rgb.r << 16) | (rgb.g << 8) | rgb.b).toString(16);
    return "#" + new Array(Math.abs(hex.length - 7)).join("0") + hex;
  };
//十六进制转RGB
var hex_to_rgb = function (hex) {
  //var rgb = {
  //    r: parseInt("0x" + hex.slice(1, 3)),
  //    g: parseInt("0x" + hex.slice(3, 5)),
  //    b: parseInt("0x" + hex.slice(5, 7))
  //}
  var rgb = new RGB(parseInt("0x" + hex.slice(1, 3)), parseInt("0x" + hex.slice(3, 5)), parseInt("0x" + hex.slice(5, 7)));
  return rgb;
};
/**
 * 计算渐变色值
 * @param peakColor {String} 峰值颜色
 * @param peakValue {Number} 峰值
 * @param targetValue {Number} 目标值
 * @param valleyColor {String} 谷值颜色，空值表示白色
 * @returns 返回十六进制字符
 */
var calc_gradient_color = function (peakColor, peakValue, targetValue, valleyColor) {
  if (!valleyColor) {
    valleyColor = "#ffffff";
  }
  var peak_rgb = convert_to_rgb(peakColor);
  var valley_rgb = convert_to_rgb(valleyColor);
  //Gradient = A + (B-A) / Step * N
  var result_rgb = new RGB(peak_rgb.r + ((valley_rgb.r - peak_rgb.r) / peakValue * (peakValue - targetValue)), peak_rgb.g + ((valley_rgb.g - peak_rgb.g) / peakValue * (peakValue - targetValue)), peak_rgb.b + ((valley_rgb.b - peak_rgb.b) / peakValue * (peakValue - targetValue)));
  result_rgb.r = limit(0, 255, result_rgb.r);
  result_rgb.g = limit(0, 255, result_rgb.g);
  result_rgb.b = limit(0, 255, result_rgb.b);
  return rgb_to_hex(result_rgb);
};
//转换颜色字符为rgb对象
var convert_to_rgb = function (str) {
  var rgb;
  if (str.toLowerCase().indexOf("rgb") >= 0) {
    str = str.replace('rgb', '').replace('(', '').replace(')', '');
    var splits = str.split(',');
    //rgb = {
    //    r: parseInt(splits[0]),
    //    g: parseInt(splits[1]),
    //    b: parseInt(splits[2])
    //}
    rgb = new RGB(parseInt(splits[0]), parseInt(splits[1]), parseInt(splits[2]));
  } else if (str.indexOf("#") === 0) {
    rgb = hex_to_rgb(str);
  }
  return rgb;
};
/**
 * 取反色
 * @param color {String} 目标颜色
 */
var invert = function (color) {
  var rgb_c = convert_to_rgb(color);
  var rgb_r = {
    r: 255 - rgb_c.r,
    g: 255 - rgb_c.g,
    b: 255 - rgb_c.b
  };
  return rgb_to_hex(rgb_r);
};

//将目标数值限制在指定范围中
const limit = function (min, max, value){
  if (value < min) {
    return min;
  }
  if (value > max) {
    return max;
  }
  return value;
};

export const colorHelper = {
  rgb_to_hex: rgb_to_hex,
  hex_to_rgb: hex_to_rgb,
  convert_to_rgb: convert_to_rgb,
  calc_gradient_color: calc_gradient_color,
  invert: invert
};

